<?php
declare (strict_types=1);

namespace app\middleware;

use app\Request;
use think\facade\Cache;
use think\facade\Db;

class GoodsDeteils
{


    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {
            $goods = Db::name('commodity_goods')
                ->field("id,name,sn,first_class,two_class,m_id,image,images,price,original_price,stock,warning,origin,output_time,brand,series,for_people,content,integral,comment,sales,express_id,FROM_UNIXTIME(created_time,'%Y-%m-%d %h:%i:%s') as created_time,status,grounding,`condition`")
                ->where(['id' => $request->param('goods_id')])
                ->find();
            //查看是否收藏
            $collect = Cache::store('redis')->sismember('Collect_' . $request->user_id, $goods['id']);
            if (!$collect) {
                $goods['is_collect'] = 0;
            } else {
                $goods['is_collect'] = 1;
            }
            if (!empty($goods['images'])) {
                $goods['images'] = explode('|', $goods['images']);
            } else {
                $goods['images'] = [];
            }
            if (empty($goods)) {
                return app('json')->json_error('商品不存在');
            }
            if ($goods['status'] != 1) {
                return app('json')->json_error('商品审核中');
            }
            if ($goods['grounding'] != 1) {
                return app('json')->json_error('商品未上架');
            }
            if ($goods['condition'] != 1) {
                return app('json')->json_error('商品已删除');
            }
            $request->goods = $goods;
            return $next($request);
        } catch (\Exception $exception) {
            return app('json')->json_error('商品不存在');
        }

    }
}
